﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelAutomationRunner
{

    /// <summary>
    /// Results in unquoted csv
    /// </summary>
    public class XLSX_to_CSV_Converter : ExcelApplicationBase
    {

        private string _inputFilePath;

        public Tuple<bool, string> XLSX_to_CSV( string inputFilePath )
        {
            _inputFilePath = inputFilePath;
            return ProcessApplication();  // calls Process below.
        }

        protected override Tuple<bool, string> Process( Application excel )
        {
            var result = DoXLSX_to_CSVConversion( excel );
            return result;
        }

        private Tuple<bool, string> DoXLSX_to_CSVConversion( Application excel )
        {
            _newPath = Path.ChangeExtension( _inputFilePath, Constants.CSV_EXTENSION );
            if ( File.Exists( _newPath ) )
            {
                return new Tuple<bool, string>( false, string.Format( Constants.CONVERTED_FILE_ALREADY_EXISTS, _newPath ) );
            }
            else
            {
                excel.Workbooks.Open( _inputFilePath );
                excel.Workbooks[1].SaveAs( _newPath, XlFileFormat.xlCSV );  // Everything 1 based
                excel.Workbooks[1].Close();
                if ( File.Exists( _newPath ) )
                {
                    return new Tuple<bool, string>( true, _newPath );
                }
                else
                {
                    return new Tuple<bool, string>( false, Constants.UNKNOWN_CONVERSION_FAILURE );
                }
            }
        }

    }
}
